﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StudentManagerDemo.Repository;

namespace StudentManagerDemo.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly HelloWorldDBContext _context;

        public HomeController(HelloWorldDBContext context)
        {
            _context = context;
        }
        [AllowAnonymous]
        public ViewResult Index()
        {
            var model = new HomePageViewModel();
            SQLEmployeeData sqlData = new SQLEmployeeData(_context);
            model.Employees = sqlData.GetAll();

            return View(model);
        }
        public ViewResult Detail(int id)
        {
            SQLEmployeeData sqlData = new SQLEmployeeData(_context);

            Employee employee = sqlData.Get(id);

            return View(employee);
        }
        [HttpGet]
        public IActionResult Edit(int id)
        {
            SQLEmployeeData sqlData = new SQLEmployeeData(_context);

            Employee employee = sqlData.Get(id);

            if (employee == null)
                return RedirectToAction("Index");

            return View(employee);
        }
        [HttpPost]
        public IActionResult Edit(int id,[FromForm] EmployeeEditViewModel input)
        {
            SQLEmployeeData sqlData = new SQLEmployeeData(_context);
            var employee = sqlData.Get(id);

            if (employee != null && ModelState.IsValid)
            {
                employee.Name = input.Name;
                _context.SaveChanges();
                return RedirectToAction("Detail", new { id = employee.ID });
            }
            return View(employee);
        }
        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(EmployeeEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                var employee = new Employee();
                employee.Name = model.Name;

                SQLEmployeeData sqlData = new SQLEmployeeData(_context);
                sqlData.Add(employee);
                return RedirectToAction("Detail", new { id = employee.ID });
            }
            return View();
        }
    }
    public class Person
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }

}
